package com.fhb.demo.myapp.youmeng;


import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.fhb.demo.myapp.R;
import com.fhb.demo.myapp.youmeng.ui.cosum.NotificationClickHandler;
import com.fhb.demo.myapp.youmeng.ui.service.MyNotificationService;
import com.fhb.demo.myapp.youmeng.ui.service.PushIntentService;
import com.fhb.demo.myapp.youmeng.ui.service.UmengNotificationService;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.common.UmLog;
import com.umeng.message.entity.UMessage;

import java.util.List;

/**
 * Created by Administrator on 2018/6/1.
 */

public class YMApplication extends Application {
    private String TAG = YMApplication.class.getSimpleName();
    public static String YMPLUSH_RECEIVERS_ACTION="com.youmeng.YMPLUSH_RECEIVERS_ACTION";

    @Override
    public void onCreate() {
        super.onCreate();
//        /***
//         * 初始化common库
//         * 参数1：上下文
//         * 参数2：设备类型 UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
//         * 参数3：推送业务的secret
//         */
//        UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE,"1fe6a20054bcef865eeb0991ee84525b");

        initUmeng();

    }

    private PushAgent mPushAgent;

    private void initUmeng() {
        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:友盟 app key
         * 参数3:友盟 channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(this,
                "5b0f5a72b27b0a247000000e",
                "FHByoument", UMConfigure.DEVICE_TYPE_PHONE,
                "81c0a529ab7150181388a1cdce88db78");
        //设置日志的开关
        UMConfigure.setLogEnabled(false);
        //设置日志的加密
        UMConfigure.setEncryptEnabled(true);
        UmLog.LOG=true;

        mPushAgent = PushAgent.getInstance(this);
//        //应用在前台时候是否显示
//        mPushAgent.setNotificaitonOnForeground(false);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.e(TAG, "device token==" + deviceToken);
                setBroadcast("success");
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e(TAG, "s==" + s + "s1==" + s1);
                setBroadcast("failure");
            }
        });
//        notifyClick();
//        customNotify();
        mPushAgent.setNotificationClickHandler(new NotificationClickHandler());
        //通知免打扰设置 在“23:00”到“7:00”之间收到通知消息时不响铃，不振动，不闪灯。
//        mPushAgent.setNoDisturbMode(23, 0, 7, 0);
//        mPushAgent.setNoDisturbMode(0, 0, 0, 0);//关闭免打扰模式：
        //同一台设备在1分钟内收到同一个应用的多条通知时，不会重复提醒，同时在通知栏里新的通知会替换掉旧的通知。可以通过如下方法来设置冷却时间：
//        mPushAgent.setMuteDurationSeconds(int seconds);
//        设置通知栏最多显示两条通知（当通知栏已经有两条通知，此时若第三条通知到达，则会把第一条通知隐藏）[0-10]：
        mPushAgent.setDisplayNotificationNumber(3);
        //MsgConstant.NOTIFICATIONPLAYSERVER（服务端控制）
//        MsgConstant.NOTIFICATIONPLAYSDKENABLE（客户端允许）
//        MsgConstant.NOTIFICATIONPLAYSDKDISABLE（客户端禁止） >
//        服务端控制：通过服务端推送状态来设置客户端响铃、震动、呼吸灯的状态 > 客户端允许：不关心服务端推送状态，客户端都会响铃、震动、呼吸灯亮 > 客户端禁止：不关心服务端推送状态，客户端不会响铃、震动、呼吸灯亮
//        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
//        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
//        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
        mPushAgent.setPushIntentServiceClass(UmengNotificationService.class);
    }
    private void setBroadcast(String flag){
        Intent intent=new Intent(YMPLUSH_RECEIVERS_ACTION);
        intent.putExtra("flag",flag);
        sendBroadcast(intent);
    }
    private void notifyClick() {
        UmengNotificationClickHandler mUmengNotificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                super.dealWithCustomAction(context, uMessage);
                Log.e(TAG, uMessage.custom);
            }
        };
        mPushAgent.setNotificationClickHandler(mUmengNotificationClickHandler);
    }

    private void customNotify() {

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public Notification getNotification(Context context, UMessage uMessage) {
                Toast.makeText(YMApplication.this, "builder_id=" + uMessage.builder_id, Toast.LENGTH_SHORT).show();

                switch (uMessage.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews mNotificationView = new RemoteViews(context.getPackageName(), R.layout.notify_custom);
                        mNotificationView.setTextViewText(R.id.tv_notifycustom_title, uMessage.title);
                        mNotificationView.setImageViewBitmap(R.id.tv_notifycustom_count,
                                getLargeIcon(context, uMessage));
                        mNotificationView.setImageViewResource(R.id.iv_notifycustom_icon,
                                getSmallIconId(context, uMessage));
                        builder.setContent(mNotificationView)
                                .setSmallIcon(getSmallIconId(context, uMessage))
                                .setTicker(uMessage.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, uMessage);

                }


            }

            @Override
            public void dealWithCustomMessage(Context context, final UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        boolean isClickOrDismissed=true;
                        if(isClickOrDismissed){
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(uMessage);
                        }else{
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(uMessage);
                        }
                        Toast.makeText(getApplicationContext(), uMessage.title, Toast.LENGTH_LONG).show();
                    }
                });
            }
        };
        mPushAgent.setMessageHandler(messageHandler);
    }
    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }
}
